<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="学校ID" prop="schoolId">
        <el-input v-model="formData.schoolId" placeholder="请输入学校ID" />
      </el-form-item>
      <el-form-item label="建筑物名称" prop="buildingName">
        <el-input v-model="formData.buildingName" placeholder="请输入建筑物名称" />
      </el-form-item>
      <el-form-item label="建筑物编码" prop="buildingCode">
        <el-input v-model="formData.buildingCode" placeholder="请输入建筑物编码" />
      </el-form-item>
      <el-form-item label="建筑类型" prop="buildingType">
        <el-select v-model="formData.buildingType" placeholder="请选择建筑类型">
          <el-option label="教学楼" value="教学楼" />
          <el-option label="实验楼" value="实验楼" />
          <el-option label="办公楼" value="办公楼" />
          <el-option label="宿舍楼" value="宿舍楼" />
          <el-option label="图书馆" value="图书馆" />
          <el-option label="体育馆" value="体育馆" />
          <el-option label="食堂" value="食堂" />
        </el-select>
      </el-form-item>
      <el-form-item label="楼层数" prop="floorCount">
        <el-input v-model="formData.floorCount" placeholder="请输入楼层数" />
      </el-form-item>
      <el-form-item label="具体位置" prop="address">
        <el-input v-model="formData.address" placeholder="请输入具体位置" />
      </el-form-item>
      <el-form-item label="管理员ID" prop="managerId">
        <el-input v-model="formData.managerId" placeholder="请输入管理员ID" />
      </el-form-item>
      <el-form-item label="建筑描述" prop="description">
        <Editor v-model="formData.description" height="150px" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="formData.status" placeholder="请选择状态">
          <el-option label="正常" :value="0" />
          <el-option label="维修" :value="1" />
          <el-option label="停用" :value="2" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { BuildingApi, Building } from '@/api/ao/building'

/** 建筑物信息 表单 */
defineOptions({ name: 'BuildingForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  buildingId: undefined,
  schoolId: undefined,
  buildingName: undefined,
  buildingCode: undefined,
  buildingType: undefined,
  floorCount: undefined,
  address: undefined,
  managerId: undefined,
  description: '', // 设置为空字符串而不是 undefined，避免富文本编辑器报错
  status: undefined,
})
const formRules = reactive({
  schoolId: [{ required: true, message: '学校ID不能为空', trigger: 'blur' }],
  buildingName: [{ required: true, message: '建筑物名称不能为空', trigger: 'blur' }],
  buildingCode: [{ required: true, message: '建筑物编码不能为空', trigger: 'blur' }],
  buildingType: [{ required: true, message: '建筑类型（教学楼/实验楼/办公楼/宿舍楼）不能为空', trigger: 'change' }],
  floorCount: [{ required: true, message: '楼层数不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态（0正常 1维修 2停用）不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await BuildingApi.getBuilding(id)
      // 确保 description 字段不为 null，避免富文本编辑器报错
      formData.value = {
        ...data,
        description: data.description || ''
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as Building
    if (formType.value === 'create') {
      await BuildingApi.createBuilding(data)
      message.success(t('common.createSuccess'))
    } else {
      await BuildingApi.updateBuilding(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    buildingId: undefined,
    schoolId: undefined,
    buildingName: undefined,
    buildingCode: undefined,
    buildingType: undefined,
    floorCount: undefined,
    address: undefined,
    managerId: undefined,
    description: '', // 设置为空字符串而不是 undefined，避免富文本编辑器报错
    status: undefined,
  }
  formRef.value?.resetFields()
}
</script>